package com.jnc.core.util;


import com.jnc.core.base.model.Menu;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: jjn
 * @Date: 2018/10/11
 * @Desc: 菜单树工具类
 */
public class TreeUtil {

    /**
     * 根据父节点的ID获取所有子节点
     * @param list
     * @param parentId 父节点ID
     * @return
     */
    public static List<Menu> getChildMenus(List<Menu> list, int parentId){
        List<Menu> resultList = new ArrayList<>();
        Iterator<Menu> iterator = list.iterator();
        while(iterator.hasNext()){
            Menu m = iterator.next();
            //根据传入的父节点ID，遍历该父节点的所有子节点
            if(m.getParentId().intValue() == parentId){
                foreachList(list, m);
                resultList.add(m);
            }
        }
        return resultList;
    }

    /**
     * 递归列表
     * @param list
     * @param m
     */
    private static void foreachList(List<Menu> list, Menu m){
        //得到子节点列表
        List<Menu> childList = getChildList(list, m);
        m.setChildren(childList);
        for (Menu child : childList){
            //判断是否有子节点
            if(hasChild(list, child)){
                Iterator<Menu> it = childList.iterator();
                while(it.hasNext()){
                    Menu t = it.next();
                    //递归获取子节点
                    foreachList(list, t);
                }
            }
        }

    }

    /**
     * 获取子节点列表
     * @param list
     * @param m
     * @return
     */
    private static List<Menu> getChildList(List<Menu> list, Menu m){
        List<Menu> childList = new ArrayList<>();
        Iterator<Menu> it = list.iterator();
        while(it.hasNext()){
            Menu t = it.next();
            if(t.getParentId().intValue() == m.getMenuId().intValue()){
                childList.add(t);
            }
        }
        return childList;
    }

    /**
     * 判断是否有子节点
     * @param list
     * @param m
     * @return
     */
    private static Boolean hasChild(List<Menu> list, Menu m){
        return getChildList(list, m).size() > 0 ? true : false;
    }
}
